package com.avcdata.aoscustommade.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.bean.LocatityCacheData;
import com.avcdata.aoscustommade.bean.UserRegionBean;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.model.SelectAgencyModel;
import com.avcdata.aoscustommade.presenter.SelectAgencyPresenter;
import com.avcdata.aoscustommade.receiver.MyReceiver;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.utils.ToastUtils;
import com.avcdata.aoscustommade.utils.http.AvcHttpUtils;
import com.avcdata.aoscustommade.utils.http.AvcJsonHttpResponseHandler;
import com.avcdata.aoscustommade.view.SelectAgencyView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by c.c on 2017/3/1.
 * 大区选择页面
 */
public class SelectBigArea_Activity extends BaseActivity implements SelectAgencyView{
    @ViewInject(R.id.leftImage)
    private ImageView leftImage;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.listview)
    private ListView listview;
    @ViewInject(R.id.area_name)
    private TextView area_nameNation;
    @ViewInject(R.id.area_state)
    private TextView area_stateNation;
    @ViewInject(R.id.quanguo)
    private View quanguo;

    @ViewInject(R.id.content_lay)
    private LinearLayout content_lay;
    @ViewInject(R.id.loadfail)
    private View loadfail;

    /**
     * 大区域数据存储
     */
    public ArrayList<UserRegionBean> areaData;
    /**
     * 办事处级数据储存
     */
    private ArrayList<ArrayList<UserRegionBean>> agencyData;
    /**
     * 详情数据存储
     */
    private ArrayList<String> detailData;

    private ArrayList<String> checkData;

    private SharedPreferencesUtils sp;

    private boolean isMain;

    private MyReceiver myReceiver;
    private SelectAgencyPresenter selectAgencyPresenter;

    @Override
    public void initView() {
        setContentView(R.layout.activity_selectbigarea);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void initInstall() {
        sp = new SharedPreferencesUtils(this);
        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver=new MyReceiver(loadfail);
        this.registerReceiver(myReceiver, filter);
//        isMain = getIntent().getBooleanExtra("isMain",false);
        title.setText(getResources().getString(R.string.select_bigarea));
        area_nameNation.setTextColor(getResources().getColor(R.color.text_one));
        area_stateNation.setVisibility(View.GONE);

        selectAgencyPresenter = new SelectAgencyPresenter(this, new SelectAgencyModel(SelectBigArea_Activity.this));

    }

    @Override
    public void initData() {
        areaData = LocatityCacheData.areaData;
        agencyData = LocatityCacheData.agencyData;
        detailData = LocatityCacheData.detailData;
        checkData = new ArrayList<>();
        loading(true);
        loadDecline();

    }


    private void loading(boolean isLoad){
        if (isLoad){
            content_lay.setVisibility(View.GONE);
            loadfail.setVisibility(View.VISIBLE);
        }else {
            content_lay.setVisibility(View.VISIBLE);
            loadfail.setVisibility(View.GONE);
        }
    }

    private void loadingTimeout() {
        loadfail.setVisibility(View.GONE);
        content_lay.setVisibility(View.GONE);
    }



    @Override
    public void evenControl() {
        leftImage.setOnClickListener(this);
        leftText.setOnClickListener(this);
        quanguo.setOnClickListener(this);
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.leftImage:
            case R.id.leftText:
                AppActivityManager.getAppManager().finishActivity(this);
                break;
            case R.id.quanguo:
                Intent intent = new Intent(SelectBigArea_Activity.this, Main_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;


        }
    }


    /**
     * 下降数据
     */
    private void loadDecline() {
        selectAgencyPresenter.loadDecline(sp.getNewWeek(), detailData);
    }

    //下降数据查询成功
    @Override
    public void loadDeclineSuccess(JSONObject jsonObject) {
       ArrayList<String> checkDataTemp = new ArrayList<>();
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                if (success && jsonObject.has("returnValue")) {
                    JSONObject returnValueObject = jsonObject.getJSONObject("returnValue");
                    Iterator iterator = returnValueObject.keys();
                    while (iterator.hasNext()) {
                        String key = iterator.next().toString().trim();
                        checkDataTemp.add(key);
                    }
                    checkData = checkDataTemp;
                    loadedType(true);
                } else {
                    loadedType(false);
                }
                loading(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //下降数据查询失败
    @Override
    public void loadDeclineFailure() {
        loading(false);
        loadedType(false);

    }
    //下降数据查询失败
    @Override
    public void loadDeclineFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException ||
                throwable instanceof SocketTimeoutException){
            loading(false);
            loadingTimeout();
        }
    }


    private void loadedType(boolean isSuccess) {
        if (isSuccess) {
            BigAreaAdapter bigAreaAdapter = new BigAreaAdapter();
            listview.setAdapter(bigAreaAdapter);

        }

    }




    private class BigAreaAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return areaData.size();
        }

        @Override
        public Object getItem(int position) {
            return areaData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressWarnings("deprecation")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(SelectBigArea_Activity.this).inflate(R.layout.item_selectarea, null);
                vHolder = new ViewHolder();
                vHolder.user_line = (ImageView) convertView.findViewById(R.id.user_line);
                vHolder.area_name = (TextView) convertView.findViewById(R.id.area_name);
                vHolder.area_state = (TextView) convertView.findViewById(R.id.area_state);
                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolder) convertView.getTag();
            }
            final UserRegionBean userRegionBean = areaData.get(position);
            vHolder.user_line.setVisibility(View.VISIBLE);
            vHolder.area_name.setText(userRegionBean.getLandName());

//            Log.e("string","------------是否升降------------"+isDecline(userRegionBean.getLandName()));
            if (isDecline(userRegionBean.getLandName())) {
                vHolder.area_state.setVisibility(View.VISIBLE);
                vHolder.area_name.setTextColor(getResources().getColor(R.color.red));

            } else {
                vHolder.area_state.setVisibility(View.GONE);
                vHolder.area_name.setTextColor(getResources().getColor(R.color.text_one));
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SelectBigArea_Activity.this, SelectAgency_Activity.class);
                    intent.putExtra("position", position);
                    intent.putExtra("are", userRegionBean.getLandName());
//                    intent.putExtra("isMain", isMain);
                    startActivity(intent);

                }
            });
            return convertView;
        }

    }


    private boolean isDecline(String string) {
        if (checkData.size() != 0) {
            for (int i = 0, j = checkData.size(); i < j; i++) {
                if (checkData.contains(string)) {
                    return true;
                }
            }
        }

        return false;
    }


    private class ViewHolder {
        ImageView user_line;
        TextView area_name;
        TextView area_state;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }

}
